<template>
	<view style="text-align: center;height: 100%;padding-top: 50px;">
		<view class="u-m-r-10" style="margin-bottom: 20px;">
			<u-avatar :src="pic" size="140"></u-avatar>
		</view>
		<view style="display: flex;flex-direction: column;align-items: center;">
			<u-cell-group style="margin-bottom: 20px;width: 80%;">
				<u-field v-model="username" label="账号" placeholder="请填写账号">
				</u-field>
			</u-cell-group>
			<u-cell-group style="margin-bottom: 20px;width: 80%;">
				<u-field password v-model="password" label="密码" placeholder="请填写密码">
				</u-field>
			</u-cell-group>
			<u-cell-group style="width: 80%;">
				<u-field v-model="validateCode" label="验证码" placeholder="请填写验证码">
					<image @click="genCode()" style="width: 70px;height: 24px;" mode="aspectFit" slot="right" :src="`data:image/jpg;base64,${base64}`"></image>
				</u-field>
			</u-cell-group>
			<u-button @click="login" shape="circle" :custom-style="{width:'100%',marginTop:'40rpx'}" type="primary"
				style="width: 86%;">
				登录</u-button>
			<u-button @click="toRegister" shape="circle" :custom-style="{width:'100%',marginTop:'40rpx'}" type="primary"
				style="width: 86%;">
				注册</u-button>
			<u-toast ref="uToast" />
		</view>
	</view>
</template>

<script>
	import {v4 as uuid} from 'uuid'
	export default {
		data() {
			return {
				base64:{},
				username:'',
				password:'',
				pic:'',
				validateCode:'',
				validateCodeId:''
			}
		},
		onLoad() {
			this.genCode()
		},
		computed: { 
			
		},
		methods: {
			toRegister() {
				uni.navigateTo({
					url: '/pages/user/register/register'
				})
			},
			login(){
				let {password,username,validateCode,validateCodeId} = this
				this.$api.userLogin({password,username,validateCode,validateCodeId}).then(res=>{
					if(res.code == 20000){
						this.$store.commit('userLogin',res.result.token)
						this.$api.getInfo({token:res.result.token}).then(res=>{
							this.$store.commit('setUserInfo',res.result)
						})
						this.$refs.uToast.show({
							title: '登录成功',
							type: 'success',
							callback(){
								uni.switchTab({
									url: '/pages/home/rent/rent'
								})
							}
						})
					}else{
						this.$refs.uToast.show({
							title: res.message,
							type: 'error'
						})
					}
				})
			},
			genCode(){
				this.validateCodeId = uuid()
				this.$api.generateValidateCode({validateCodeId:this.validateCodeId}).then(res=>{
					this.base64 = res.result
				}) 
			}
		}
	}
</script>

<style>
	page {
		background-color: #ededed;
	}
</style>
